import { any } from 'codelyzer/util/function';
import { Headers, Http, Jsonp , RequestMethod, RequestOptionsArgs, Response, RequestOptions, ResponseContentType, URLSearchParams, BaseRequestOptions } from '@angular/http';
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';

// import * as filesave from 'file-saver';
import { UtilService, localURl } from './util';
// import { localArea } from './localarea';

@Injectable()
export class ApiService {
    // public Alerts = new AlertService();
    private devURL: string;
    private localURl = localURl;
    private carURl = 'carbrandmodelseries';

    constructor(
        private http: Http,
        private util: UtilService,
        private httpClient: HttpClient,
        private jsonp: Jsonp,
        // public Alerts:AlertService
    ) {
        this.devURL = this.util.bate_dev("bate");
        console.log(this.devURL);
        this.digui(init_option);
        // this.getlocalArea();
    }
    //统一的方法所有的请求都走这个方法
    public promise(url: string, option?: RequestOptionsArgs): Promise<Response> {
        let urls;
        option = option || { method: RequestMethod.Get }//这边会给一个请求的方式  默认请求是get
        if (url.indexOf('http') == -1) {
            urls = this.devURL.concat(url);
        } else {
            urls = url;
        }
        // urls = devURL.concat(url);
        //判断有没有用户的存在。是否存在登录异常
        // let user: UserInfo = new UserInfo();
        if (url.indexOf('login') == -1) {
            option.headers = option.headers || new Headers();
            option.headers.append('token', `Bearer ${this.getLocalStroage()}`);
            option.headers.append('projectCode', "YYZX");
        }
        return this.http.request(urls, option).toPromise();
    }

    public promised(url: string, option?: RequestOptionsArgs): Promise<Response> {
        let urls = url;
        option = option || { method: RequestMethod.Get }//这边会给一个请求的方式  默认请求是get
        return this.http.request(urls, option).toPromise();
    }
    findAct(url: string, search?: any) {
        return this.promised(url, { method: RequestMethod.Get, search: search })
            // .then(resp => this.extractData(resp))
            // .catch(resp => this.handleError(resp))
    }
    jsonpGet(url: string, search?: any){
        return this.jsonp.get(url,{search:search}).map(res=>res.json);
    }

    get(url: string, search?: any) {
        return this.promise(url, { method: RequestMethod.Get, search: search })
            .then(resp => this.extractData(resp))
            .catch(resp => this.handleError(resp))
    }
    post(url: string, body: any) {
        return this.promise(url, { method: RequestMethod.Post, body: body })
            .then(resp => this.extractData(resp))
            .catch(resp => this.handleError(resp))
    }
    post2(url: string, body: any) {
        return this.promise(url, { method: RequestMethod.Post, search: body })
            .then(resp => this.extractData(resp))
            .catch(resp => this.handleError(resp))
    }
    put(url: string, search: any) {
        return this.promise(url, { method: RequestMethod.Put, body: search })
            .then(resp => this.extractData(resp))
            .catch(resp => this.handleError(resp))
    }

    put2(url: string, search: any) {
        return this.promise(url, { method: RequestMethod.Put, search: search })
            .then(resp => this.extractData(resp))
            .catch(resp => this.handleError(resp))
    }
    Postformdata(url: string, body: any) {
        return this.promise(url, new RequestOptions({
            method: RequestMethod.Post,
            body: this.buildURLSearchParams(body),
            headers: new Headers({
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            })
        }))
            .then(resp => this.extractData(resp))
            .catch(resp => this.handleError(resp))
    }
    public uploadimg(url, file) {
        let formdate = new FormData(file);
        // let url = this.imgurl;
        return this.http.post(url, formdate).toPromise()
            .then(res => this.extractData(res))
            .catch(err => this.handleError(err))
    }
    patch(url: string, body: any) {
        return this.promise(url, { method: RequestMethod.Patch, body: body })
            .then(resp => this.extractData(resp))
            .catch(resp => this.handleError(resp))
    }
    delete(url: string) {
        return this.promise(url, { method: RequestMethod.Delete })
            .then(resp => this.extractData(resp))
            .catch(resp => this.handleError(resp));
    }
    delete2(url: string, body?: any) {
        return this.promise(url, { method: RequestMethod.Delete, body: body })
            .then(resp => this.extractData(resp))
            .catch(resp => this.handleError(resp));
    }

    createRequestOption = (req?: any): BaseRequestOptions => {
        const options: BaseRequestOptions = new BaseRequestOptions();
        if (req) {
            const params: URLSearchParams = new URLSearchParams();
            params.set('pageIndex', req.pageIndex);
            params.set('pageSize', req.pageSize);
            options.params = params;
        }
        return options;
    };

    //下载
    downlode(url: string, search?: any, fileName?: string) {
        return this.promise(url, { method: RequestMethod.Get, search: search, responseType: ResponseContentType.Blob }).then(res => {
            let data = res.blob();
            // filesave.saveAs(data, fileName);
        })
    }
    //保存token
    public setLocalStroage(body) {
        let token = "token";
        if (body) {
            // console.log(body)
            localStorage.setItem(token, JSON.stringify(body));
        }
    }
    //获得token
    public getLocalStroage() {
        let token = JSON.parse(localStorage.getItem("token"));
        // console.log(token);
        return token;
    }


    //清除token
    public clearLocalStroage() {
        // localStorage.removeItem(TOKEN);
    }
    //序列化formdate
    public buildURLSearchParams(paramMap) {
        let params = new URLSearchParams();
        if (!paramMap) {
            return params;
        }
        for (let key in paramMap) {
            let val = paramMap[key];
            params.set(key, val);
        }
        return params;
    }
    public extractData(res) {
        // console.log(res);
        let text = res.text();
        if (!text) return;
        let data = res.json();
        if (!data) return;
        let result = data;
        if (!result) {
            throw new TypeError('返回对象类型转换失败！');
        }
        return result;
    }
    public handleError(error: any) {
        console.log('An error occurred', error); // for demo purposes only
        let res = JSON.parse(error._body);
        console.log(res.code)
        if (res.errcode != 0) {
            console.log("错误");
            // this.Alerts.error(res);
        }
        //错误信息的返回值
        return Promise.reject(error.message || error);
    }
    //时间转换
    public formatDateTime(date) {
        // function isNull(data){ 
        if (date == "" || date == undefined || date == null) {
            return null;
        }
        // return (data == "" || data == undefined || data == null) ? "暂无" : data; 
        // }
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        minute = minute < 10 ? ('0' + minute) : minute;
        var second = date.getSeconds();
        second = second < 10 ? ('0' + second) : second;
        return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
    };

    //时间转换2
    public formatDateTime2(date) {
        let date1 = date + '0'
        if (date1.indexOf('-')>-1){
            return date;
        }
        // function isNull(data){ 
        if (date == "" || date == undefined || date == null) {
            return null;
        }
        // return (data == "" || data == undefined || data == null) ? "暂无" : data; 
        // }
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        return y + '-' + m + '-' + d;
    };

    // 车辆品牌获取
    getCarAll() {
        return this.promise(this.carURl, { method: RequestMethod.Get })
            .then(resp => this.localdata(this.extractData(resp)))
            .catch(resp => this.handleError(resp))
    }

    //地区获取
    getlocalArea() {
        return this.promise(this.localURl, { method: RequestMethod.Get })
            .then(resp => this.localdata2(this.extractData(resp)))
            .catch(resp => this.handleError(resp))
    }
    //地区处理方式
    localdata(result) {
        // console.log(result);
        let data = result.result.data;
        console.log(data);
        let local = [], province, citys, areas;
        for (let i = 0; i < data.length; i++) {
            province = this.AreaData(data[i]);
            let city = data[i][3];
            // console.log(cit    y);
            province.children = [];
            for (let j = 0; j < city.length; j++) {
                citys = this.AreaData(city[j]);
                // console.log(citys);
                let area = city[j][3];
                citys.children = [];
                for (let k = 0; k < area.length; k++) {
                    areas = this.AreaData(area[k]);
                    areas.isLeaf = true;
                    citys.children.push(areas);
                }
                province.children.push(citys);
            }
            local.push(province);
        }
        return local;
    }
    //数组拼接 省市区
    AreaData(data) {
        let temp = { id: 0, label: '', value: '', children: [] }
        temp.id = data[0];
        temp.label = data[1];
        temp.value = data[2];
        temp.children = data[3];
        return temp;
    }
    //省市区 方法递归
    localdata2(data){
        let datas=data.result.data;

        let local=[];
        for(let i=0;i<datas.length;i++){
            local.push(this.localdigui(datas[i]));
        }
        return local;
        // console.log('111------111l---localdigui')
        // console.log(local);
    }
    localdigui(data){
        // console.log(data);
        let  result={
            id:data[0],
            label:data[1],
            value:data[2],
        }
        if(Array.isArray(data[3])){
            result['children']=data[3].map(item=>this.localdigui(item));
        }else {
            result['isLeaf']=true;
        }
        return result;
    }

    //递归方法 原始数据 整理之后的数据类型
    private arrayobj = [];
    digui(nowObj) {
        console.log(nowObj);
        for (let i = 0; i < nowObj.length; i++) {
            this.arrayobj.push(this.digui2(nowObj[i]));
        }
        console.log("111----1111");
        console.log(this.arrayobj);
    }
    digui2(obj) {
        let tem = {
            val: obj.value,
            label: obj.label,
        }
        if (Array.isArray(obj.children)) {
            //递归的正确思想 
            tem['children'] = obj.children.map(item => this.digui2(item))
        }else {
            tem['isLeaf']=true;
        }
        return tem;
    }
    getCarType(){
        let url = "car/findcarmodels";
        this.get(url)
            .then( res =>{
                console.log(res);
                return res.result;
            })
    }

    getCompany(){
        let url = "findlogcoms";
        this.get(url).then(res => 
            {return res.result}
        );
    }

}
const init_options = [{
    value: 'zhejiang',
    label: 'Zhejiang',
    children: [{
        value: 'hangzhou',
        label: 'Hangzhou',
        children: [{
            value: 'xihu',
            label: 'West Lake',
            isLeaf: true
        }],
    }, {
        value: 'ningbo',
        label: 'Ningbo',
        isLeaf: true
    }],
}, {
    value: 'jiangsu',
    label: 'Jiangsu',
    children: [{
        value: 'nanjing',
        label: 'Nanjing',
        children: [{
            value: 'zhonghuamen',
            label: 'Zhong Hua Men',
            isLeaf: true
        }],
    }],
}];
const init_option = [{
    value: 'zhejiang',
    label: 'Zhejiang',
    children: [{
        value: 'hangzhou',
        label: 'Hangzhou',
        children: [{
            value: 'xihu',
            label: 'West Lake',
        }],
    }, {
        value: 'ningbo',
        label: 'Ningbo',
    }],
}, {
    value: 'jiangsu',
    label: 'Jiangsu',
    children: [{
        value: 'nanjing',
        label: 'Nanjing',
        children: [{
            value: 'zhonghuamen',
            label: 'Zhong Hua Men',
        }],
    }],
}];